package com.wolf.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.wolf.common.constant.AuthServerConstant;
import com.wolf.common.enume.BizCodeEnum;
import com.wolf.common.utils.R;
import com.wolf.common.vo.MemberEntityVo;
import com.wolf.gulimall.auth.feign.MemberFeignService;
import com.wolf.gulimall.auth.feign.ThirdPartFeignService;
import com.wolf.gulimall.auth.vo.UserLoginVo;
import com.wolf.gulimall.auth.vo.UserRegisteredVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 登录控制层
 */
@Slf4j
@Controller
public class LoginController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 发送验证码
     *
     * @param phone 手机号
     * @return 是否发送成功
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //防止同一个手机号多次发送验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        String code = (int) ((Math.random() * 9 + 1) * 100000)+"";
        String submit = code +"_" + System.currentTimeMillis();
        //redis缓存验证码,十分钟有效期,缓存的目的是进行验证码校验
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, submit, 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 注册
     *
     * @param userRegisteredVo   注册参数
     * @param result             JSR303校验错误信息
     * @param model              视图
     * @param redirectAttributes 重定向方式携带数据访问
     * @return 跳转页面
     */
    @PostMapping("/registered")
    public String registered(@Valid UserRegisteredVo userRegisteredVo, BindingResult result, Model model, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//             model.addAttribute("errors",errors);
            //重定向方式携带数据访问 redirectAttributes,利用的是session的原理进行数据传输的
            redirectAttributes.addFlashAttribute("errors", errors);
            //@Valid 开启数据校验,数据校验有问题,转发到注册页面
            return "redirect:http://auth.gulimallwolf.com/reg.html";
        }
        //校验验证码
        String code = userRegisteredVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisteredVo.getPhone());
        if (!StringUtils.isEmpty(s) && code.equals(s.split("_")[0])) {
            //删除缓存中的验证码,令牌机制
            stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisteredVo.getPhone());
            //验证码校验通过,调用远程服务进行注册
            R r = memberFeignService.registered(userRegisteredVo);
            if (r.getCode() == 0) {
                //注册成功返回登录页面
                return "redirect:http://auth.gulimallwolf.com/login.html";
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg",r.getData(new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimallwolf.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码校验错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错,跳转到注册页面
            return "redirect:http://auth.gulimallwolf.com/reg.html";
        }
    }


    /**
     * 用户账号密码登录
     * @param userLoginVo 用户信息
     * @param redirectAttributes 重定向方式携带数据访问
     * @param httpSession session
     * @return 返回登录成功/失败页面
     */
    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession httpSession){
        //这里并不是提交一个JSON数据,而是kv键值对,所以参数没有加@RequestBody 注解
        //远程登录
        R login = memberFeignService.login(userLoginVo);
        if(login.getCode() == 0){
            //登录成功 TODO 登录成功后处理
            MemberEntityVo memberEntityVo = login.getData("data", new TypeReference<MemberEntityVo>() {});
            //将用户信息放入session 存储到redis中
            httpSession.setAttribute(AuthServerConstant.LOGIN_USER,memberEntityVo);
            return "redirect:http://gulimallwolf.com";
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimallwolf.com/login.html";
        }
    }

    /**
     * 登录页
     * @param httpSession session
     * @return 跳转页面地址
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession httpSession){
        if(httpSession.getAttribute(AuthServerConstant.LOGIN_USER) == null){
            //判断用户是否已经登录,已经登录的用户直接跳转到首页,没有登录的进行登录
            return "login";
        }else{
            return "redirect:http://gulimallwolf.com";
        }
    }

}
